<!-- src/views/student/Dashboard.vue -->
<template>
  <div class="student-dashboard">
    <h1>学生仪表板</h1>

    <!-- 个人信息卡片 -->
    <el-row :gutter="20" class="profile-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog"
                >
                  编辑信息
                </el-button>
              </div>
            </div>
          </template>
          <div class="profile-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="学号">{{ profile.studentId || profile.studentNumber }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ profile.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ getGenderLabel(profile.gender) }}</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ profile.birthDate }}</el-descriptions-item>
              <el-descriptions-item label="专业">{{ profile.major }}</el-descriptions-item>
              <el-descriptions-item label="年级">{{ profile.grade }}</el-descriptions-item>
              <el-descriptions-item label="班级">{{ profile.className }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ profile.phone }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ profile.email }}</el-descriptions-item>
            </el-descriptions>

            <div class="resume-section">
              <h3>简历附件</h3>
              <el-upload
                class="upload-demo"
                action="/api/students/resume"
                :on-success="handleResumeUploadSuccess"
                :on-error="handleResumeUploadError"
                :file-list="resumeFileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 当前实习信息 -->
    <el-row :gutter="20" class="internship-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>当前实习信息</span>
            </div>
          </template>
          <div v-if="currentInternships && currentInternships.length > 0" class="internship-info">
            <!-- 显示所有进行中的实习 -->
            <div v-for="internship in currentInternships" :key="internship.id" class="internship-item">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="实习企业">{{ internship.companyName }}</el-descriptions-item>
                <el-descriptions-item label="实习岗位">{{ internship.positionTitle }}</el-descriptions-item>
                <el-descriptions-item label="指导教师">{{ internship.teacherName }}</el-descriptions-item>
                <el-descriptions-item label="企业导师">{{ internship.mentorName }}</el-descriptions-item>
                <el-descriptions-item label="开始日期">{{ formatDate(internship.startDate) }}</el-descriptions-item>
                <el-descriptions-item label="结束日期">{{ formatDate(internship.endDate) }}</el-descriptions-item>
                <el-descriptions-item label="实习状态">
                  <el-tag :type="getInternshipStatusType(internship.status)">
                    {{ getInternshipStatusLabel(internship.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="实习成绩" v-if="internship.finalScore">
                  <el-tag type="success">{{ internship.finalScore }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          <div v-else>
            <p>暂无实习信息</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-row :gutter="20" class="actions-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="navigateTo('/student/positions')">浏览实习岗位</el-button>
            <el-button type="success" @click="navigateTo('/student/applications')">实习申请管理</el-button>
            <el-button type="warning" @click="navigateTo('/student/materials')">实习材料提交</el-button>
            <el-button type="info" @click="navigateTo('/student/grades')">查看实习成绩</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 个人信息编辑对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑个人信息"
    width="600px"
    @close="resetEditForm"
  >
    <el-form
      :model="editForm"
      :rules="editRules"
      ref="editFormRef"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学号" prop="studentNumber">
            <el-input v-model="editForm.studentNumber" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="editForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" :value="1" />
              <el-option label="女" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="editForm.birthDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择出生日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="专业" prop="major">
            <el-input v-model="editForm.major" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年级" prop="grade">
            <el-input v-model="editForm.grade" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="班级" prop="className">
            <el-input v-model="editForm.className" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="头像" prop="avatar">
            <el-input v-model="editForm.avatar" placeholder="请输入头像URL" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="简历" prop="resume">
        <el-input v-model="editForm.resume" type="textarea" placeholder="请输入简历信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm" :loading="editLoading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useStudentStore } from '../../store/student'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const studentStore = useStudentStore()
const router = useRouter()

const profile = ref({})
const currentInternships = ref([])
const resumeFileList = ref([])
const editLoading = ref(false)

// 对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref()

// 编辑表单
const editForm = reactive({
  studentNumber: '',
  name: '',
  gender: null,
  birthDate: '',
  major: '',
  grade: '',
  className: '',
  phone: '',
  email: '',
  avatar: '',
  resume: ''
})

// 表单验证规则
const editRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
  className: [{ required: true, message: '请输入班级', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 显示编辑对话框
const showEditDialog = () => {
  // 填充表单数据
  Object.keys(editForm).forEach(key => {
    editForm[key] = profile.value[key] || ''
  })
  editDialogVisible.value = true
}

// 重置编辑表单
const resetEditForm = () => {
  Object.keys(editForm).forEach(key => {
    editForm[key] = profile.value[key] || ''
  })
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        // 分离学生信息和用户信息
        const studentData = {
          studentNumber: editForm.studentNumber,
          name: editForm.name,
          gender: editForm.gender,
          birthDate: editForm.birthDate,
          major: editForm.major,
          grade: editForm.grade,
          className: editForm.className,
          avatar: editForm.avatar,
          resume: editForm.resume
        }

        const userData = {
          phone: editForm.phone,
          email: editForm.email
        }

        // 更新学生信息
        await studentStore.updateProfile(studentData)

        // 更新用户信息
        await studentStore.updateUserProfile(userData)

        ElMessage.success('个人信息更新成功')
        editDialogVisible.value = false
        await fetchAllProfileData()
      } catch (error) {
        ElMessage.error(error.message || '个人信息更新失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

// 获取性别标签
const getGenderLabel = (gender) => {
  if (gender === 1) return '男'
  if (gender === 0) return '女'
  return '未知'
}

// 获取学生信息
const fetchAllProfileData = async () => {
  try {
    // 获取学生信息
    await studentStore.fetchProfile()
    const studentProfile = studentStore.profile

    // 获取用户信息（包括电话和邮箱）
    const userProfile = await studentStore.fetchUserProfile()

    // 合并信息
    profile.value = {
      ...studentProfile,
      phone: userProfile.phone,
      email: userProfile.email
    }

    // 如果有简历，则显示在文件列表中
    if (profile.value.resumeUrl) {
      resumeFileList.value = [{
        name: '简历.pdf',
        url: profile.value.resumeUrl
      }]
    }
  } catch (error) {
    ElMessage.error('获取个人信息失败')
  }
}

// 获取当前实习信息
const fetchCurrentInternship = async () => {
  try {
    // 使用新的接口获取学生的实习信息
    const response = await studentStore.fetchMyInternships()
    // 处理返回的数据，添加成绩信息
    if (response && response.content) {
      const internshipsWithScores = await Promise.all(response.content.map(async (internship) => {
        try {
          // 获取实习成绩
          const evaluationResponse = await studentStore.getFinalEvaluation(internship.id)
          // 计算综合成绩
          let finalScore = null
          if (evaluationResponse.teacherEvaluation || evaluationResponse.companyEvaluation) {
            const teacherScore = evaluationResponse.teacherEvaluation?.score || 0
            const companyScore = evaluationResponse.companyEvaluation?.score || 0
            finalScore = ((teacherScore + companyScore) / 2).toFixed(1)
          }
          return {
            ...internship,
            finalScore
          }
        } catch (error) {
          // 如果获取成绩失败，返回原始实习信息
          return internship
        }
      }))
      currentInternships.value = internshipsWithScores
    } else {
      currentInternships.value = []
    }
  } catch (error) {
    // 发生错误时设置为空数组，不显示错误信息
    currentInternships.value = []
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 处理简历上传成功
const handleResumeUploadSuccess = (response, file, fileList) => {
  ElMessage.success('简历上传成功')
  // 更新用户信息
  fetchAllProfileData()
}

// 处理简历上传失败
const handleResumeUploadError = (error, file, fileList) => {
  ElMessage.error('简历上传失败')
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 获取实习状态标签类型
const getInternshipStatusType = (status) => {
  switch (status) {
    case 0: return 'info'     // 未开始
    case 1: return 'warning'  // 进行中
    case 2: return 'success'  // 已完成
    default: return ''
  }
}

// 获取实习状态标签文本
const getInternshipStatusLabel = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    default: return '未知'
  }
}

onMounted(() => {
  fetchAllProfileData()
  fetchCurrentInternship()
})
</script>

<style scoped>
.student-dashboard {
  padding: 20px;
}

.card-header {
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.profile-content,
.internship-info {
  margin-bottom: 20px;
}

.resume-section {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.internship-item {
  margin-bottom: 15px;
}

.internship-item:last-child {
  margin-bottom: 0;
}
</style>
